package com.hebeiwangxiaozhang.user.service.service;

import com.alibaba.fastjson.JSONObject;
import com.hebeiwangxiaozhang.response.CommonResponse;
import com.hebeiwangxiaozhang.response.ResponseCode;
import com.hebeiwangxiaozhang.response.ResponseUtils;
import com.hebeiwangxiaozhang.user.service.config.GiteeConfig;
import com.hebeiwangxiaozhang.user.service.pojo.OauthClient;
import com.hebeiwangxiaozhang.user.service.pojo.User;
import com.hebeiwangxiaozhang.user.service.repo.OauthClientRepository;
import com.hebeiwangxiaozhang.user.service.repo.UserRepository;
import com.hebeiwangxiaozhang.user.service.utils.RedisCommonProcessor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/*
1. 补充user信息，save的时候 set全面，检查
2. 全局唯一Id 生成，新增user id
3. User 登录成功后，将user信息存入 redis，前端携带 userid 在header中，后续可以通过userid 做限流
 */

//no need oauth
@Service
public class UserInfoService {

    @Autowired
    private RestTemplate innerRestTemplate;

    @Autowired
    private RedisCommonProcessor redisCommonProcessor;

    @Autowired
    private UserRepository userRepository;

    public CommonResponse checkPhoneBindStatus(String personId) {
        User user = (User) redisCommonProcessor.get(personId);
        boolean isBind = false;
        if(user != null) {
            isBind = user.getUserPhone() != null;
            return ResponseUtils.okResponse(isBind);
        }
        Integer userId = Integer.valueOf(personId) - 10000000;
        Optional<User> userOptional = userRepository.findById(userId);
        if(userOptional.isPresent()) {
            isBind = userOptional.get().getUserPhone() != null;
            redisCommonProcessor.set(personId, userOptional.get(), 1296000);
            return ResponseUtils.okResponse(isBind);
        }
        return ResponseUtils.failResponse(ResponseCode.BAD_REQUEST.getCode(), null, "Invalid personId!");
    }

    public CommonResponse bindPhoneNumber(String personId, String phoneNumber, String code) {
        //删除redis缓存
        //canal 模块再次删除
        //验证code 没有问题的话，存入数据库
        String cacheCode = String.valueOf(redisCommonProcessor.get(phoneNumber));
        if(StringUtils.isEmpty(cacheCode)) {
            return ResponseUtils.failResponse(ResponseCode.BAD_REQUEST.getCode(), null,
                    "Phone verify-code is expired!");
        }
        if(!cacheCode.equals(code)) {
            return ResponseUtils.failResponse(ResponseCode.BAD_REQUEST.getCode(), null,
                    "Phone verify-code is incorrect!");
        }
        userRepository.updateUserPhoneNumberById(phoneNumber, Integer.valueOf(personId) - 10000000);
        return ResponseUtils.okResponse(null);
    }

    public CommonResponse getUserInfoByToken(String token) {
        Map results =
                innerRestTemplate.getForObject("http://oauth2-service/oauth/check_token?token=" + token, Map.class);
        boolean active = Boolean.valueOf(String.valueOf(results.get("active")));
        if (!active) {
            return ResponseUtils.failResponse(ResponseCode.UNAUTHORIZED.getCode(), null, "token is not active");
        }
        String username = String.valueOf(results.get("user_name"));
        return ResponseUtils.okResponse(new HashMap(){{put("username", username);}});
    }
}
